//
//  JSTSystemInfo.m
//  JSTMobClick
//
//  Created by Czj on 16/8/28.
//  Copyright © 2016年 Czj. All rights reserved.
//

#import "JSTSystemInfo.h"
#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/sockio.h>
#include <net/if.h>
#include <errno.h>
#include <net/if_dl.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <AdSupport/AdSupport.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <ifaddrs.h>
#import <arpa/inet.h>

@implementation JSTSystemInfo

+ (NSString *)osVersion
{
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)uuid
{
    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}

+ (NSString *)screenScale
{
    NSString *scaleStr = nil;
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize size = rect.size;
    CGFloat width = size.width;
    CGFloat height = size.height;
    scaleStr = [NSString stringWithFormat:@"%.0fx%.0f", width, height];
    return scaleStr;
}

+ (BOOL)isIosVersionBelow5
{
    if ([[JSTSystemInfo iosVersion] floatValue] < 5.0) {
        return YES;
    }
    return NO;
}

+ (BOOL)isIosVersionBelow7
{
    if ([[JSTSystemInfo iosVersion] floatValue] < 7.0) {
        return YES;
    }
    return NO;
}

+ (NSString *)iosVersion
{
    return [[UIDevice currentDevice] systemVersion];
}

+ (NSString *)platform
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    return platform;
}

+ (NSString *)platformString
{
    NSString *platform = [self platform];
    
    if ([platform isEqualToString:@"iPhone1,1"])   return @"iPhone1G GSM";
    if ([platform isEqualToString:@"iPhone1,2"])   return @"iPhone3G GSM";
    if ([platform isEqualToString:@"iPhone2,1"])   return @"iPhone3GS GSM";
    if ([platform isEqualToString:@"iPhone3,1"])   return @"iPhone4 GSM";
    if ([platform isEqualToString:@"iPhone3,3"])   return @"iPhone4 CDMA";
    if ([platform isEqualToString:@"iPhone4,1"])   return @"iPhone4S";
    if ([platform isEqualToString:@"iPhone5,1"])   return @"iPhone5";
    if ([platform isEqualToString:@"iPhone5,2"])   return @"iPhone5";
    if ([platform isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
    if ([platform isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (Global)";
    if ([platform isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"])    return @"iPhone 6 (A1549/A1586)";
    if ([platform isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus (MNFU2CH/A)";
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad1 WiFi";
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad2 WiFi";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad2 GSM";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad2 CDMAV";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad2 CDMAS";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad mini WiFi";
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad3 WiFi";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad3 GSM";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad3 CDMA";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4 (GSM)";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    if ([platform isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
    if ([platform isEqualToString:@"iPad4,2"])      return @"iPad Air (GSM)";
    if ([platform isEqualToString:@"iPad4,4"])      return @"iPad Mini Retina (WiFi)";
    if ([platform isEqualToString:@"iPad4,5"])      return @"iPad Mini Retina (GSM)";
    if ([platform isEqualToString:@"i386"] || [platform isEqualToString:@"x86_64"])
        return @"iPhone Simulator";
    
    return platform;
    
}

//获取系统当前时间
+ (NSString *)systemTimeInfo
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateString = [dateFormatter stringFromDate:[NSDate date]];
    return currentDateString;
}

+ (NSString *)appVersion
{
    NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    return [NSString stringWithFormat:@"%@", version];
}

+ (BOOL)is_iPhone_5
{
    if ([UIScreen mainScreen].bounds.size.height == 568.0f) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark -
#pragma mark jailbreaker

static const char * __jb_app = NULL;

+ (BOOL)isJailBroken
{
    /*
    static const char * __jb_apps[] =
    {
        "/Application/Cydia.app",
        "/Application/limera1n.app",
        "/Application/greenpois0n.app",
        "/Application/blackra1n.app",
        "/Application/blacksn0w.app",
        "/Application/redsn0w.app",
        NULL
    };
    
    __jb_app = NULL;
    
    // method 1
    for ( int i = 0; __jb_apps[i]; ++i )
    {
        if ( [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:__jb_apps[i]]] )
        {
            __jb_app = __jb_apps[i];
            return YES;
        }
    }
    
    // method 2
    if ( [[NSFileManager defaultManager] fileExistsAtPath:@"/private/var/lib/apt/"] )
    {
        return YES;
    }
    
    // method 3
    if ( 0 == system("ls") )
    {
        return YES;
    }
    */
    return NO;
}

+ (NSString *)jailBreaker
{
    if ( __jb_app )
    {
        return [NSString stringWithUTF8String:__jb_app];
    }
    else
    {
        return @"";
    }
}

+ (BOOL)checkDevice:(NSString *)device
{
    NSString *deviceType = [UIDevice currentDevice].model;
    NSRange range = [deviceType rangeOfString:device];
    return range.location != NSNotFound;
}

+ (NSString *)getMacAddress
{
    int                 mgmtInfoBase[6];
    char                *msgBuffer = NULL;
    size_t              length;
    unsigned char       macAddress[6];
    struct if_msghdr    *interfaceMsgStruct;
    struct sockaddr_dl  *socketStruct;
    NSString            *errorFlag = NULL;
    
    // Setup the management Information Base (mib)
    mgmtInfoBase[0] = CTL_NET;        // Request network subsystem
    mgmtInfoBase[1] = AF_ROUTE;       // Routing table info
    mgmtInfoBase[2] = 0;
    mgmtInfoBase[3] = AF_LINK;        // Request link layer information
    mgmtInfoBase[4] = NET_RT_IFLIST;  // Request all configured interfaces
    
    // With all configured interfaces requested, get handle index
    if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
        errorFlag = @"if_nametoindex failure";
    else
    {
        // Get the size of the data available (store in len)
        if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
            errorFlag = @"sysctl mgmtInfoBase failure";
        else
        {
            // Alloc memory based on above call
            if ((msgBuffer = malloc(length)) == NULL)
                errorFlag = @"buffer allocation failure";
            else
            {
                // Get system information, store in buffer
                if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
                    errorFlag = @"sysctl msgBuffer failure";
            }
        }
    }
    
    // Befor going any further...
    if (errorFlag != NULL)
    {
        
        return errorFlag;
    }
    
    // Map msgbuffer to interface message structure
    interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
    
    // Map to link-level socket structure
    socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
    
    // Copy link layer address data in socket structure to an array
    memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
    
    // Read from char array into a string object, into traditional Mac address format
    NSString *macAddressString = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x",
                                  macAddress[0], macAddress[1], macAddress[2],
                                  macAddress[3], macAddress[4], macAddress[5]];
    
    
    // Release the buffer memory
    free(msgBuffer);
    
    return macAddressString;
}


+ (NSString *)getCurrentNet
{
    NSString *result;
    KYReachability *r = [KYReachability reachabilityWithHostName:@"www.apple.com"];
    
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            return @"0";
            break;
        case ReachableViaWiFi:
            result = @"1";
            break;
        case ReachableViaWWAN:{
            // 获取手机网络类型
            CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
            
            NSString *currentStatus = info.currentRadioAccessTechnology;
            
            if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
                
                result = @"2";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
                
                result = @"3";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
                
                result = @"3";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
                
                result = @"4";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
                
                result = @"4";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
                result = @"2";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
                
                result = @"3";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
                
                result = @"3";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
                
                result = @"3";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
                
                result = @"4";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
                
                result = @"4";
            }
        }
            break;
        default:
            break;
    }
    return result;
}



+ (NSString *)getIpAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}

+ (NSMutableDictionary *)getUserDictionary
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:[self appVersion] forKey:@"appVersion"];              //app 版本号
    [dic setValue:[self iosVersion] forKey:@"appSystemVersion"];        //手机系统版本
    [dic setValue:[self platformString] forKey:@"platformString"];      //手机型号
    [dic setValue:[self getMacAddress] forKey:@"macAddress"];           //mac地址
    [dic setValue:[self screenScale] forKey:@"screenScale"];            //屏幕分辨率
    [dic setValue:[self uuid] forKey:@"uuid"];                          //uuid
    [dic setValue:[self getCurrentNet] forKey:@"currentNet"];           //当前网络状况
    [dic setValue:[self getIpAddress] forKey:@"ipAddress"];             //ip地址
    
    return dic;
}

- (NSArray *)runningProcesses {
    
    int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
    size_t miblen = 4;
    
    size_t size;
    int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
    
    struct kinfo_proc * process = NULL;
    struct kinfo_proc * newprocess = NULL;
    
    do {
        
        size += size / 10;
        newprocess = realloc(process, size);
        
        if (!newprocess){
            
            if (process){
                free(process);
            }
            
            return nil;
        }
        
        process = newprocess;
        st = sysctl(mib, miblen, process, &size, NULL, 0);
        
    } while (st == -1 && errno == ENOMEM);
    
    if (st == 0){
        
        if (size % sizeof(struct kinfo_proc) == 0){
            int nprocess = size / sizeof(struct kinfo_proc);
            
            if (nprocess){
                
                NSMutableArray * array = [[NSMutableArray alloc] init];
                
                for (int i = nprocess - 1; i >= 0; i--){
                    
                    NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
                    NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
                    
                    NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
                                                                        forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName", nil]];
                }
                
                free(process);
                return array;
            }
        }
    }
    return nil;
}

//判断是否有sim卡
+ (NSString *) isSIM
{
//    if([CTSIMSupportGetSIMStatus() isEqualToString:kCTSIMSupportSIMStatusNotInserted]){
//        return @"0";
//    }else{
//        return @"1";
//    }
    return @"1";
}

//获取运营商
+ (NSString *) carrierName
{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [info subscriberCellularProvider];
    NSString *mCarrier = [NSString stringWithFormat:@"%@",[carrier carrierName]];
    if (IsStrEmpty(mCarrier)) {
        mCarrier = @"";
    }
    return mCarrier;
}

//获取idfa
+ (NSString *) adid
{
    NSString *adid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return adid;
}

//获取ssid
+ (NSString *) createSSID
{
    NSString *ssid = @"Not Found";
    NSString *macIp = @"Not Found";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            
            ssid = [dict valueForKey:@"SSID"];
            macIp = [dict valueForKey:@"BSSID"];
        }
    }
    return ssid;
}

//获取bssid
+ (NSString *) createBSSID
{
    NSString *ssid = @"Not Found";
    NSString *macIp = @"Not Found";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            ssid = [dict valueForKey:@"SSID"];
            macIp = [dict valueForKey:@"BSSID"];
        }
    }
    return macIp;
}

//应用唯一标识
+ (NSString *) applicationIdentifier
{
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
    NSMutableDictionary *writeInfoDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return [writeInfoDic valueForKey:@"bunldId"];
}

//应用名称
+ (NSString *) applicationName
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
    NSMutableDictionary *writeInfoDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return [writeInfoDic valueForKey:@"appName"];
}

// 所属人qq
+ (NSString *) userQQ
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
    NSMutableDictionary *writeInfoDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return [writeInfoDic valueForKey:@"qqStr"];
}

// 所属人邮箱
+ (NSString *) userEmail
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
    NSMutableDictionary *writeInfoDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return [writeInfoDic valueForKey:@"emailStr"];
}

//应用版本
+ (NSString *) applicationVersion
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
    NSMutableDictionary *writeInfoDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return [writeInfoDic valueForKey:@"appVersion"];
}

//当前设备语言
+ (NSString *)getCurrentLanguage
{
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    if (currentLanguage.length >2) {
        currentLanguage = [currentLanguage substringWithRange:NSMakeRange(0, 2)];
    }
    return currentLanguage;
}

//屏幕宽
+ (NSString *)screenWidth
{
    CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize size = rect.size;
    return [NSString stringWithFormat:@"%.f", size.width];
}
//屏幕高
+ (NSString *)screenHeight
{
    CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize size = rect.size;
    return [NSString stringWithFormat:@"%.f", size.height];
}

+ (NSString *)userAddress
{
    if (IsStrEmpty([JSTLocation sharedInstace].address)) {
        return @"";
    }
//    NSString *str = [JSTLocation sharedInstace].address;
    return [JSTLocation sharedInstace].address;
}

//+ (NSString *) userlongitute
//{
//    if (IsStrEmpty([JSTLocation sharedInstace].longitude)) {
//        return @"";
//    }
//    return [JSTLocation sharedInstace].longitude;
//}
//
//+ (NSString *) userlatitude
//{
//    if (IsStrEmpty([JSTLocation sharedInstace].latitude)) {
//        return @"";
//    }
//    return [JSTLocation sharedInstace].latitude;
//}

+ (NSString *) userKey
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
    NSMutableDictionary *writeDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return [writeDic valueForKey:@"appKey"];
}

+ (void)saveAppInstallTime{
    if(![[NSUserDefaults standardUserDefaults] valueForKey:@"appInstallTime"]){
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%ld", (long)a];
        [[NSUserDefaults standardUserDefaults] setValue:timeString forKey:@"appInstallTime"];
    }
}
+(void)saveToken:(NSString *)token{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
+ (NSString *)token{
    return  [[NSUserDefaults standardUserDefaults] valueForKey: @"token"];
}
+ (NSString *) getAppInstallTime
{
    return  [[NSUserDefaults standardUserDefaults] valueForKey: @"appInstallTime"];
}
+ (NSString *) sdkVersion{
    return [NSString stringWithFormat:@"2.0"];
}
/* 从url中获取内容 */
+ (NSMutableDictionary *)urlToContent:(NSString *)urlString
{
    if (IsStrEmpty(urlString)) return nil;
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    //切割字符串
    //第1次问号切割"?"
    NSArray *firsrArr = [urlString componentsSeparatedByString:@"?"];
    //第2次问号切割"&"
    NSArray *secArr = [[firsrArr lastObject] componentsSeparatedByString:@"&"];
    //第3次问号切割"="
    if (secArr.count > 0) {
        for (NSString *string in secArr) {
            NSArray *thrArr = [string componentsSeparatedByString:@"="];
            [paramDic setValue:thrArr[1] forKey:thrArr[0]];
        }
    }
    return paramDic;
}
// 判断程序是否第一次进入
+ (BOOL) isFirlst
{
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        return YES;
    }else{
        return NO;
    }
}

+ (NSString *)URLDecodedString:(NSString *)str
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

+(NSString*)encodeString:(NSString*)unencodedString
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

+ (NSString *) getTypeId:(NSString *)typeId
{
    NSString *str;
    switch (typeId.integerValue) {
            case 1011:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(120)];
            break;
            case 1010:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(150)];
            break;
            case 1009:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(300)];
            break;
            case 1008:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(110)];
            break;
            case 1007:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(100)];
            break;
            case 1000:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(320)];
            break;
            case 22:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(120)];
            break;
            case 21:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(250)];
            break;
            case 19:
                return [NSString stringWithFormat:@"%.f", kCurrentScreenWidth(150)];
            break;
            
        default:
            break;
    }
    return str;
}

+ (JSTHomePageModel *)currentModel
{
    static JSTHomePageModel *currentModel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        currentModel = [[JSTHomePageModel alloc] init];
    });
    return currentModel;
}
+ (NSString *)updateVersion
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"updateVersion"];
}

+ (NSString *) currentProjectVersion
{
    return @"2";
}

+ (NSMutableDictionary *)advertFilteredDic
{
    static NSMutableDictionary *filteredDic = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        filteredDic = [NSMutableDictionary dictionary];
    });
    return filteredDic;
}

+ (NSMutableArray *)advertFilteredStrData
{
    static NSMutableArray *arr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        arr = [NSMutableArray array];
    });
    return arr;
}

+ (NSMutableArray *)advertFilteredIdData
{
    static NSMutableArray *arr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        arr = [NSMutableArray array];
    });
    return arr;
}
// 将 nil null 等空字段转换为""
+ (NSString *)getStr:(id)obj
{
    NSString *str = [NSString stringWithFormat:@"%@", obj];
    if (IsStrEmpty(str)) {
        str = @"";
    }
    return str;
}
// 判断是否已同意版本声明
+ (NSString *)isAgree
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"agreeNotification"];
}
// 提取app类型
+ (NSString *) appType
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
    NSMutableDictionary *writeInfoDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    return [writeInfoDic valueForKey:@"appType"];
}
// 提取极光推送appKey
+ (NSString *)JPushAppKey
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"systemConfig"];
    if(IsArrEmpty(configDic)) return nil;
    return [configDic valueForKey:@"jpush_appkey"];
}
/*保存用户经纬度信息*/
+ (void) saveUserLongitude:(NSString *)longitude latitude:(NSString *)latitude{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setObject:longitude forKey:@"longitude"];
    [userDf setObject:latitude forKey:@"latitude"];
    [userDf synchronize];
}

/*获取用户经纬度信息*/
+ (NSString *)userLongitude{
    return  [[NSUserDefaults standardUserDefaults] objectForKey:@"longitude"];
}
/*获取用户经纬度信息*/
+ (NSString *)userLatitude{
    return  [[NSUserDefaults standardUserDefaults] objectForKey:@"latitude"];
}
// 提取域名
+ (NSString *)webUrl
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"systemConfig"];
    if (IsStrEmpty([configDic valueForKey:@"app_website"])) {
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"ProjectData" ofType:@"plist"];
        NSMutableDictionary *writeInfoDic = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
        NSLog(@"---- newUrlStr = %@", [writeInfoDic valueForKey:@"urlStr"]);
        return [writeInfoDic valueForKey:@"urlStr"];
    }
    return [configDic valueForKey:@"app_website"];
}
// 提取广告时间间隔
+ (int) advertInterval
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"systemConfig"];
    if (IsStrEmpty([configDic valueForKey:@"interval_time"])) {
        return 180;
    }
    return [[configDic valueForKey:@"interval_time"] intValue]/1000;
}
// 存储bannerId
+ (void)getBannerId:(NSString *)bannerId
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:bannerId forKey:@"bannerId"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 提取banner广告位
+ (NSString *) bannerId
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"bannerId"];
}
// 提取阅读器广告状态
+ (NSString *) bannerStatus
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"readerConfig"];
    return [configDic valueForKey:@"reader_advplace"];
}
// 提取阅读器小说标题 标签
+ (NSString *) readerTitle
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"readerConfig"];
    return [configDic valueForKey:@"reader_title"];
}
// 提取阅读器小说内容 标签
+ (NSString *) readerText
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"readerConfig"];
    return [configDic valueForKey:@"reader_content"];
}
// 提取阅读器上一页 标签
+ (NSString *) readerPrevious
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"readerConfig"];
    return [configDic valueForKey:@"reader_previous"];
}
// 提取阅读器下一页 标签
+ (NSString *) readerNext
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"readerConfig"];
    return [configDic valueForKey:@"reader_next"];
}
// 提取分享类型
+ (NSString *) shareType
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"shareConfig"];
    DLog(@"--- type = %@", [configDic valueForKey:@"share_type"]);
    return [configDic valueForKey:@"share_type"];
}
// 提取qr开关
+ (BOOL) qrScanIsOpen{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"qrConfig"];
    NSString *qrset = [NSString stringWithFormat:@"%@",[configDic valueForKey:@"qrcode_set"]];
    return [qrset isEqualToString:@"1"]?YES:NO;
}
// 提取qr按钮id
+ (NSString *) qrScanId{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"qrConfig"];
    NSString *qrId = [NSString stringWithFormat:@"%@",[configDic valueForKey:@"qrcode_id"]];
    return qrId;
}
// 存储系统配置信息
+ (void) getSystemConfig:(NSDictionary *) dic
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:dic forKey:@"systemConfig"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 存储分享配置信息
+ (void) getShareConfig:(NSDictionary *) dic
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:dic forKey:@"shareConfig"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 存储阅读器配置信息
+ (void) getReaderConfig:(NSDictionary *) dic
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:dic forKey:@"readerConfig"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 存储二维码配置信息
+ (void) getqrConfig:(NSDictionary *) dic
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:dic forKey:@"qrConfig"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 存储底部tabbar配置信息
+ (void) getFunctionConfig:(NSDictionary *) dic{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:dic forKey:@"app_function"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 存储app状态信息
+ (void) saveAppStatus:(NSDictionary *)statusDic{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:statusDic forKey:@"system_value"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 获取app状态信息
+ (BOOL) appStatus{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"system_value"];
    if (IsArrEmpty(configDic)) {
        return YES;
    }else{
        if ([[NSString stringWithFormat:@"%@",configDic[@"appStatus"]] isEqualToString:@"0"]) {
            return NO;
        }else{
            return YES;
        };
    }
}
// 获取app提示信息
+ (NSString *) appStatusMsg{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"system_value"];
    return IsStrEmpty(configDic[@"appMsg"])?(@"app不可用"):configDic[@"appMsg"];
}
// 是否打开侧边栏
+ (BOOL) isOpenSileMenu{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"system_value"];
    return configDic[@"sideSlipStatu"];
}
// 是否打开底部Tabbar
+ (BOOL) isOpenTabbar{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"app_function"];
    if ([configDic[@"open"] isEqualToString:@"off"]) {
        return NO;
    }else{
        return YES;
    }
    
}
+ (NSString *)base64EncodedStringWithstr:(NSString *)str
{
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return [data base64EncodedStringWithOptions:0];
}

+ (NSString *)base64DecodedStringWithEncodestr:(NSString *)encodestr
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:encodestr options:0];
    return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}

+ (UIColor *) backStatusColor
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"systemConfig"];
    if (IsStrEmpty([configDic valueForKey:@"color"] )||[[configDic valueForKey:@"color"] isEqualToString:@"#000000"]||[[configDic valueForKey:@"color"] isEqualToString:@"<null>"])
    {
        return [UIColor blackColor];
    }
    return [UIColor colorWithHexString:[configDic valueForKey:@"color"]];
}

+ (BOOL)isOpenHistory{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"systemConfig"];
    if (IsArrEmpty(configDic)) {
        return NO;
    }else{
        if ([[NSString stringWithFormat:@"%@",configDic[@"history"]] isEqualToString:@"1"]) {
            return YES;
        }else{
            return NO;
        };
    }
}

+ (BOOL)isLoadTabbar{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    NSDictionary *configDic = [userDf valueForKey:@"systemConfig"];
    if (IsArrEmpty(configDic)) {
        return NO;
    }else{
        if ([[NSString stringWithFormat:@"%@",configDic[@"ios_tabbar"]] isEqualToString:@"1"]) {
            return YES;
        } else{
            return NO;
        };
    }
}
// 储存当前url 作为最后地址
+ (void)getCurrentUrl:(NSString *)url
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf removeObjectForKey:@"lastUrl"];
    [userDf setValue:url forKey:@"lastUrl"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
// 获取最后地址
+ (NSString *) lastUrl
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"lastUrl"];
}

#warning - NO 新增必须修改
+ (NSString *)iphoneNum
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"iphoneNum"];
}

#warning - 后续从服务端获取信息
+ (NSString *)imKey
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"imKey"];
}

+ (void)cacheIphoneNum:(NSString *)iphoneNum
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf removeObjectForKey:@"iphoneNum"];
    [userDf setValue:iphoneNum forKey:@"iphoneNum"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)cacheUserDict:(NSDictionary *)dict
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:dict forKey:@"userModel"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSDictionary *)userDict
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"userModel"];
}

+ (void)cacheLoginToken:(NSString *)loginToken
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf setValue:loginToken forKey:@"loginToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)cacheImKey:(NSString *)imKey
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    [userDf removeObjectForKey:@"imKey"];
    [userDf setValue:imKey forKey:@"imKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *)loginToken
{
    NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
    return [userDf valueForKey:@"loginToken"];
}

@end

@implementation NSString (Public_NSString)

+ (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font CGsize:(CGSize)CGsize
{
    CGRect rect = [string boundingRectWithSize:CGsize//限制最大的宽度和高度
                                       options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin//采用换行模式
                                    attributes:@{NSFontAttributeName: font}//传入的字体字典
                                       context:nil];
    return rect.size;
}

@end
